package arithmetic.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁实现
 * @author jiangfeng 2019/7/15 15:02
 */
public class MySpinLock {

    private AtomicReference<Thread> atomicReference = new AtomicReference<>();

    private void lock(){
        Thread thread = Thread.currentThread();
        System.out.println("--"+thread.getName()+"进入...");
        while (!atomicReference.compareAndSet(null, thread)) {
            //是空才能进去, 没进入就一直自旋不断获取
        }
        System.out.println("--"+thread.getName()+"拿到锁...");

    }

    private void unLock(){
        Thread thread = Thread.currentThread();
        System.out.println("--"+thread.getName()+"要解锁...");
        atomicReference.compareAndSet(thread,null);

    }

    public static void main(String[] args) {
        MySpinLock mySpinLock = new MySpinLock();
        new Thread(()->{
            mySpinLock.lock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mySpinLock.unLock();
        },"t1").start();

        new Thread(()->{
            mySpinLock.lock();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mySpinLock.unLock();
        },"t2").start();
    }
}
